const process = require("../models/project_process");
const formidable = require("formidable");

var express = require("express");
const { reject, resolve } = require("bluebird");
var router = express.Router();

// 添加步骤
router.post('/', (req, res) => {
    var form = formidable.IncomingForm();
    form.parse(req, (err, fields) => {
        if (err) {
            res.json({ 'state': false, 'msg': err });
        }else {
            var process_num = () => {
                return new Promise(resolve => {
                    process.count({
                        project_id: fields.project_id,
                        process: fields.process
                    }, (error, count) => {
                        if (error) {
                            res.json({'state': fail, 'msg': error});
                        }else {
                            resolve({count});
                        }
                    });
                });
            };

            var update_seq = (param) => {
                return new Promise((resolve) => {
                    var count = param.count;
                    if (fields.sequence != count) {
                        process.updateMany(
                            {
                                project_id: fields.project_id,
                                process: fields.process,
                                sequence: {$gte: fields.sequence}
                            },
                            {$inc: {sequence: 1}}, 
                            {}, 
                            (e, doc) => {
                                if (e) {
                                    res.json({ 'state': false, 'msg': e });
                                }else {
                                    resolve({doc});
                                }
                            }
                        );
                    }else {
                        resolve("no update");
                    }
                });
            };

            process_num().then(update_seq).then(() => {
                process.create({
                    project_id: fields.project_id,  //对应项目id
                    process: fields.process,  //对应步骤序号
                    sequence: fields.sequence,  //小步骤序号
                    title: fields.title,  //小步骤标题
                    content: fields.content,  //小步骤内容
                    point_ids: fields.point_ids,  //包含知识点列表，元素为String
                    ctime:  new Date().getTime(),  //创建时间戳
                    mtime: new Date().getTime()  //修改时间戳
                }, (error) => {
                    if (error) {
                        res.json({ 'state': false, 'msg': error });
                    }else {
                        res.json({ 'state': true, 'msg': 'add process success' });
                    }
                });
            });
        }
    });
});

// 修改步骤
router.put('/:id', (req, res) => {
    var form = formidable.IncomingForm();
    form.parse(req, (err, fields) => {
        if (err) {
            res.json({ 'state': false, 'msg': err });
        }else {
            process.findByIdAndUpdate(req.params.id, {
                title: fields.title,
                content: fields.content,
                point_ids: fields.point_ids
            }, {}, e => {
                if (e) {
                    res.json({ 'state': false, 'msg': e });
                }else {
                    res.json({ 'state': true, 'msg': 'update process success' });
                }
            })
        }
    });
});

// 删除项目步骤
router.delete('/:id', (req, res) => {
    var get_seq = () => {
        return new Promise(resolve => {
            process.findById(req.params.id, (err, doc) => {
                if (err) res.json({ 'state': false, 'msg': err });
                else {
                    resolve({
                        seq: doc.sequence,
                        project_id: doc.project_id,
                        process: doc.process
                    });
                }
            })
        });
    }
    var update_seq = (param) => {
        return new Promise((resolve) => {
            var seq = param.seq;
            process.updateMany(
                {
                    project_id: param.project_id,
                    process: param.process,
                    sequence: {$gt: seq}
                },
                {$inc: {sequence: -1}}, 
                {}, 
                (e, doc) => {
                    if (e) {
                        res.json({ 'state': false, 'msg': e });
                    }else {
                        resolve({doc});
                    }
                }
            );
        });
    };

    get_seq().then(update_seq).then(() => {
        process.remove({_id: req.params.id}, error => {
            if (error) res.json({ 'state': false, 'msg': error });
            else res.json({'state': true, 'msg': 'delete process success'});
        })
    });
});

//获取项目
router.get('/', (req, res) => {
    var query = req.query;
    if (query.project_id && query.process == null && query.sequence == null) {
        process.find({
            project_id: query.project_id
        }).sort({sequence: 1}).exec((e, doc) => {
            if (e) res.json({ 'state': false, 'msg': e });
            else res.json({'state': true, 'msg': 'find process success', 'data': doc});
        });
    }
    else if (query.process && query.sequence == null) {
        process.find({
            project_id: query.project_id,
            process: query.process
        }).sort({sequence: 1}).exec((e, doc) => {
            if (e) res.json({ 'state': false, 'msg': e });
            else res.json({'state': true, 'msg': 'find process success', 'data': doc});
        });
    }else if (query.sequence) {
        process.find({
            project_id: query.project_id,
            process: query.process,
            sequence: query.sequence
        }).sort({sequence: 1}).exec((e, doc) => {
            if (e) res.json({ 'state': false, 'msg': e });
            else res.json({'state': true, 'msg': 'find process success', 'data': doc});
        });
    }
})


module.exports = router;